#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
MySQL数据库连接检查脚本
用于验证MySQL数据库配置是否正确
"""

import sys
import os
from sqlalchemy import create_engine, text
from config import settings

def check_mysql_connection():
    """
    检查MySQL数据库连接
    
    Returns:
        bool: 连接是否成功
    """
    print("=" * 50)
    print("MySQL 数据库连接检查")
    print("=" * 50)
    
    try:
        # 获取数据库URL
        database_url = settings.DATABASE_URL
        print(f"数据库URL: {database_url}")
        
        # 检查是否为MySQL连接
        if not database_url.startswith(('mysql', 'mysql+pymysql')):
            print("❌ 错误: 当前配置不是MySQL数据库")
            print(f"当前数据库类型: {database_url.split('://')[0]}")
            print("请在 .env 文件中配置MySQL连接字符串")
            return False
        
        # 创建数据库引擎
        print("\n正在连接数据库...")
        engine = create_engine(database_url)
        
        # 测试连接
        with engine.connect() as connection:
            # 执行简单查询
            result = connection.execute(text("SELECT VERSION() as version"))
            version = result.fetchone()[0]
            print(f"✅ 连接成功!")
            print(f"MySQL版本: {version}")
            
            # 检查数据库
            result = connection.execute(text("SELECT DATABASE() as db_name"))
            db_name = result.fetchone()[0]
            print(f"当前数据库: {db_name}")
            
            # 检查字符集
            result = connection.execute(text(
                "SELECT @@character_set_database as charset, @@collation_database as collation"
            ))
            charset_info = result.fetchone()
            print(f"字符集: {charset_info[0]}")
            print(f"排序规则: {charset_info[1]}")
            
            # 检查表是否存在
            result = connection.execute(text(
                "SELECT COUNT(*) as table_count FROM information_schema.tables WHERE table_schema = DATABASE()"
            ))
            table_count = result.fetchone()[0]
            print(f"数据库表数量: {table_count}")
            
            if table_count == 0:
                print("\n⚠️  数据库为空，请运行以下命令初始化数据:")
                print("python init_data.py")
            else:
                print("\n✅ 数据库已包含数据表")
            
        return True
        
    except Exception as e:
        print(f"❌ 连接失败: {str(e)}")
        print("\n可能的解决方案:")
        print("1. 检查MySQL服务是否启动")
        print("2. 验证数据库连接参数（用户名、密码、主机、端口）")
        print("3. 确认数据库 'aihub_db' 是否存在")
        print("4. 检查防火墙设置")
        print("5. 运行 setup_mysql.sql 脚本创建数据库")
        return False

def check_mysql_requirements():
    """
    检查MySQL相关依赖是否安装
    
    Returns:
        bool: 依赖是否完整
    """
    print("\n" + "=" * 50)
    print("MySQL 依赖检查")
    print("=" * 50)
    
    required_packages = ['pymysql', 'mysqlclient']
    missing_packages = []
    
    for package in required_packages:
        try:
            __import__(package)
            print(f"✅ {package} 已安装")
        except ImportError:
            print(f"❌ {package} 未安装")
            missing_packages.append(package)
    
    if missing_packages:
        print(f"\n请安装缺失的依赖包:")
        print(f"pip install {' '.join(missing_packages)}")
        return False
    
    print("\n✅ 所有MySQL依赖已安装")
    return True

def show_mysql_setup_guide():
    """
    显示MySQL设置指南
    """
    print("\n" + "=" * 50)
    print("MySQL 设置指南")
    print("=" * 50)
    
    print("""
1. 安装MySQL服务器:
   - 下载并安装MySQL Community Server
   - 或使用包管理器: choco install mysql (Windows)

2. 启动MySQL服务:
   - Windows: net start mysql
   - 或通过服务管理器启动

3. 创建数据库:
   mysql -u root -p < setup_mysql.sql

4. 配置环境变量 (.env 文件):
   DATABASE_URL=mysql+pymysql://root:your_password@localhost:3306/aihub_db?charset=utf8mb4

5. 安装Python依赖:
   pip install pymysql mysqlclient

6. 初始化数据:
   python init_data.py
""")

def main():
    """
    主函数
    """
    # 检查依赖
    deps_ok = check_mysql_requirements()
    
    if not deps_ok:
        print("\n请先安装必要的依赖包")
        return
    
    # 检查连接
    connection_ok = check_mysql_connection()
    
    if not connection_ok:
        show_mysql_setup_guide()
        return
    
    print("\n" + "=" * 50)
    print("✅ MySQL配置检查完成，一切正常!")
    print("=" * 50)
    print("\n可以开始使用应用了:")
    print("python main.py")

if __name__ == "__main__":
    main()